# -*- coding: utf-8 -*-

'''
 :author: Rayco Abad-Martín <rayco.abad@gmail.com>
 :author: Elena Marrero-Méndez <elemarez@gmail.com>
'''

from yacf.Backends.Common.Visitors.GenericVisitors import * 
from Backends.MPI.Mutators.Common import AbstractMPIMutator
from yacf.Frontend.Shortcuts import getCurrentLanguageAst
from yacf.Frontend.SymbolTable import updateSymbolTableFromNode
from yacf.Tools.Tree import InsertTool, RemoveTool, ReplaceTool
import config

c_ast = getCurrentLanguageAst()

class MPI_MainCreatorFilter(GenericFilterVisitor):
    """ Returns the first node with the given attribute
    """
    def __init__(self):
        def condition(node):
            if type(node) == c_ast.FuncDef:
               if node.decl.name == 'main':
                  return True
            return False
        super(MPI_MainCreatorFilter, self).__init__(condition_func = condition)

class MPI_MainCreator(AbstractMPIMutator):
    """ Apply MPI Main """ 
    def __init__(self, *args, **kwargs):
        super(MPI_MainCreator, self).__init__()

    def filter(self, ast):
        """ Filter """
        raise NotImplemented

    def filter_iterator(self, ast):
        """ Filter iterator """
        return NotImplemented

    def fast_filter(self, ast):
        """ Fast filter , looking for binary expressions """
        return MPI_MainCreatorFilter().dfs_iter(ast)

    def mutatorFunction(self, ast):
        """ Mutator code 
            :param ast: node returned by the filter
        """
        ast.decl.name = 'llc_main'
        template_code = open(config.WORKDIR + '/Backends/MPI/Templates/main.tmpl', 'r').read()
        main = self.parse_snippet(template_code, {}, name = 'template main', show = False)
        InsertTool(subtree = main, position = "end").apply(ast.parent, 'ext')
        updateSymbolTableFromNode(ast)
        return ast
